const jwt = require('jsonwebtoken')

// 加解操作密钥
const secret_key = 'CAR_SHOW'
// 有效期默认一天
const validity_time = 60*60*24

// 签署token令牌,默认有效期为24小时
const encrypt = (userId,pwd = secret_key,time = validity_time) => {
    const token = jwt.sign(
        {userId},
        pwd,
        {expiresIn: time}
    )
    return token
}

// 判断是否有token令牌,如果有则解析，没有则直接向客户端返回无效token,返回值为布尔值
const hasToken = (ctx) => {
    const token = ctx.headers['authorization'] ;
    let result = false
    if(token){
        jwt.verify(token,secret_key,(err,decode) => {
            if(err){
                console.log(err);
                ctx.body = {
                    code: 401,
                    msg: '无效token',
                    data: []
                }
                result = false
            }else{
               result = decode.userId
            }
        })
    }else{
        ctx.body = {
            code: 402,
            msg: '未包含token的无效请求',
            data: []
        }
        result = false
    }
    return result
}

module.exports = {
    encrypt,
    hasToken
}
